﻿using System;
using System.Linq;
using XRM.Security.DataAccess;
using XRM.Security.DataAccess.Enums;
using XRM.Security.WebUI.Helpers;

namespace XRM.Security.WebUI.Models.Report.ReportBuilder
{
    public class RequestByWorkKindReportBuilder : ReportBuilderBase
    {
        private readonly IDataManager _dataManager;
        public override string TemplateFileName
        {
            get { return "Перечень заявок (по видам работ)"; }
        }

        public RequestByWorkKindReportBuilder( IDataManager dataManager )
        {
            _dataManager = dataManager;
        }

        public override string Create(CreateReportModel model)
        {
            var startDate = model.StartPeriod == null ? DateTime.Today : model.StartPeriod.Value;
            var endDate = model.EndPeriod == null ? DateTime.Today : model.EndPeriod.Value;
            var selectedWorkKinds = model.GetSelectedCheckBoxValues().ToList();
            var searchEndDate = endDate.AddDays( 1 );
            var requests = _dataManager.RequestRepository.GetAll( s => s.CreateDate >= startDate && s.CreateDate < searchEndDate ).SelectMany( s => s.RequestWorkKinds )
                .Where( s => selectedWorkKinds.Contains( s.WorkKindId ) )
                .GroupBy( s => s.WorkKind.WorkKindName )
                .ToDictionary( s => s.Key, s => new
                    {
                        ClosedRequestCount = s.Count( g => g.Request.Status == (int)RequestStatus.Closed ),
                        OpenRequestCount = s.Count( g => g.Request.Status == (int)RequestStatus.InPart || g.Request.Status == (int)RequestStatus.InWork )
                    } );
            var workKinds = _dataManager.WorkKindRepository.GetAll(s => selectedWorkKinds.Contains(s.WorkKindId))
                .OrderBy(s => s.WorkKindName).Select(s => new RequestsReportTypeRequest {WorkKind = s.WorkKindName}).ToList();
            foreach (var workKind in workKinds)
            {
                if (requests.ContainsKey(workKind.WorkKind))
                {
                    workKind.PerformedRequestAmount = requests[workKind.WorkKind].ClosedRequestCount.ToString();
                    workKind.RequestAmount = requests[workKind.WorkKind].OpenRequestCount.ToString();
                }
                else
                {
                    workKind.PerformedRequestAmount = "0";
                    workKind.RequestAmount = "0";
                }
            }
            var report = new RequestsReportType
                {
                    CreateDate = DateTime.Now,
                    StartDate = startDate,
                    EndDate = endDate,
                    Request = workKinds.ToArray()
                };
            return CreateXlsxDocument( Utils.SerializeToString( report ) );
        }
    }
}